package com.weitu.train.certificate.controller;

import com.weitu.accessory.bean.AccessoryPackageInfo;
import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.user.entity.User;
import com.weitu.permission.user.entity.UserDuty;
import com.weitu.permission.user.entity.UserDepartment;
import com.weitu.permission.user.service.UserService;
import com.weitu.plugin.PageView;
import com.weitu.train.certificate.entity.Certificate;
import com.weitu.train.certificate.entity.PersonFile;
import com.weitu.train.certificate.service.CertificateService;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * Created by WT-SUN on 2017/5/12.
 */
@Controller
@RequestMapping(value = "train/certificate")
public class CertificateController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "train/certificate/";

    @Autowired
    private CertificateService certificateService;

    @Autowired
    private AccessoryUtilService accessoryUtilService;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/list")
    public String list() {
        return MODULE_BATH_PATH + "list";
    }

    /**
     * 员工培训档案
     * @return
     */
    @RequestMapping(value = "/files")
    public String files() {
        return MODULE_BATH_PATH + "files";
    }

    @RequestMapping(value = "/add")
    public String add() {
        return MODULE_BATH_PATH + "add";
    }

    /**
     * 员工培训档案详情
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/fileInfo", method = RequestMethod.GET)
    public String fileInfo(Model model, String id) {
        User user = userService.selectById(id);

        //有职位时拼接所有职位字符串
        if (user.getUserDutyList().size() > 0) {
            String duties = "";
            for (UserDuty userDuty : user.getUserDutyList()) {
                duties += "," + userDuty.getDutyName();
            }
            duties = duties.substring(1);
            model.addAttribute("duties", duties);
        }

        if (user.getUserDepartmentList().size() > 0) {
            String deptName = "";
            for (UserDepartment department: user.getUserDepartmentList()) {
                deptName += "," + department.getDeptName();
            }
            deptName = deptName.substring(1);
            model.addAttribute("deptName", deptName);
        }
        model.addAttribute(user);
        return MODULE_BATH_PATH + "/fileInfo";
    }

    @ResponseBody
    @RequestMapping("insertData")
    @SystemLog(module = "培训管理——证书管理", methods = "新增证书")
    @Transactional
    public AjaxResult insertData(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> paramMap = new HashMap<String, Object>();
        getAddBasicFieldMap(paramMap);
        paramMap.put("delState",0);
        String rId=paramMap.get("id").toString();
        boolean accFlag= AccessoryUtil.saveAccerssoryInfo(rId);
        boolean boo=certificateService.insertCertificate(paramMap);
        if (boo) {
            return success("添加成功");
        }else {
            return fail("添加失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/CerTable", method = RequestMethod.POST)
    public Object CerTable(HttpServletRequest request) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);
        int totalNum=certificateService.selectAllCertificateCount(paramMap);
        DataGridPagination dataGridPagination=DataGridPagination.getInstance(request,totalNum);
        PageView pageView=dataGridPagination.getPageView();
        if (paramMap.get("sort") == null) {
            pageView.setSortColumn("addTime");
        }
        paramMap.put("pageView", pageView);
        List<Certificate> certificates =certificateService.selectAllCertificate(paramMap);
        Object data=dataGridPagination.flushDataGridData(certificates);
        return data;
    }


    /**
     * 编辑与详情页面
     * @param id
     * @param type
     * @return
     */
    @RequestMapping("info")
    public ModelAndView info(String id,  String type) {
        ModelAndView modelAndView = new ModelAndView();
        Certificate certificate =certificateService.selectById(id);
        List<AccessoryPackageInfo> accessoryList =  accessoryUtilService.queryAccessoryByBusinessId(id);
        modelAndView.addObject("ce", certificate);
        modelAndView.addObject("accessoryList",accessoryList);
        if (type.equals("info")) {
            modelAndView.setViewName(MODULE_BATH_PATH + "info");
        } else {
            modelAndView.setViewName(MODULE_BATH_PATH + "edit");
        }
        return modelAndView;
    }

    /**
     * 证书记录
     * @param certificateId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/selectRecords", method = RequestMethod.POST)
    public List<Map<String,Object>> selectRecords(String certificateId)throws Exception{
        return certificateService.selectRecords(certificateId);
    }

    /**
     * 员工培训档案 培训记录
     * @param userId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/selectRecordsByUserId", method = RequestMethod.POST)
    public List<Map<String,Object>> selectRecordsByUserId(String userId)throws Exception{
        return certificateService.selectRecordsByUserId(userId);
    }

    /**
     * 持证信息
     * @param userId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/selectCertByUserId", method = RequestMethod.POST)
    public List<Map<String,Object>> selectCertByUserId(String userId)throws Exception{
        return certificateService.selectCertByUserId(userId);
    }

    @ResponseBody
    @RequestMapping("updateData")
    @Transactional(readOnly = false)
    @SystemLog(module = "证书管理——证书登记", methods = "更新证书记录")
    public AjaxResult updateData() {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        getEditBasicFieldMap(paramMap);
        User loginUser = getSessionUser();
        String loginUserId = loginUser.getId();
        String loginUserDeptId = loginUser.getDepartment().getId();
        paramMap.put("addUserId", loginUserId);
        paramMap.put("addDeptId", loginUserDeptId);
        paramMap.put("delState",0);
        boolean boo=certificateService.updateCertificate(paramMap);
        if (boo) {
            boolean accFlag= AccessoryUtil.saveAccerssoryInfo(paramMap.get("id").toString());
            if (accFlag){
                return success("更新成功");
            }else {
                return fail("更新失败");
            }
        } else {
            return fail("更新失败");
        }
    }

    /**
     * 员工培训档案
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/FileTable", method = RequestMethod.POST)
    public Object FileTable(HttpServletRequest request) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);
        if (paramMap.get("year")!=null&&!"".equals(paramMap.get("year").toString())) {
            String yearStr="";
            String[] years=null;
            if (paramMap.get("year")instanceof String){
                yearStr=paramMap.get("year").toString();
            }else {
                List<String> conIds=(List<String>)paramMap.get("year");
                if(conIds!=null&& !"".equals(conIds)){
                    String yearStr1="";
                    if (conIds.size()>0){
                        for (String conid:conIds){
                            yearStr1+=","+conid;
                        }
                        yearStr=yearStr1.substring(1);
                    }
                }
            }
            years=yearStr.split(",");
            paramMap.put("years",years);
        }
        int totalNum=certificateService.selectFilesCount(paramMap);
        DataGridPagination dataGridPagination=DataGridPagination.getInstance(request,totalNum);
        PageView pageView=dataGridPagination.getPageView();
        if (paramMap.get("sort") == null) {
            pageView.setSortColumn("addTime");
        }
        paramMap.put("pageView", pageView);
        List<PersonFile> certificates =certificateService.selectFiles(paramMap);
        Object data=dataGridPagination.flushDataGridData(certificates);
        return data;
    }
}
